<template>
  <div class="admin-container">
    <h1>系统管理</h1>

    <div class="admin-stats">
      <div class="stat-card">
        <h3>用户总数</h3>
        <p class="stat-number">{{ stats.totalUsers }}</p>
      </div>
      <div class="stat-card">
        <h3>教师用户</h3>
        <p class="stat-number">{{ stats.teacherUsers }}</p>
      </div>
      <div class="stat-card">
        <h3>学生用户</h3>
        <p class="stat-number">{{ stats.studentUsers }}</p>
      </div>
      <div class="stat-card">
        <h3>备课计划</h3>
        <p class="stat-number">{{ stats.totalTasks }}</p>
      </div>
    </div>

    <div class="admin-tabs">
      <div
        v-for="tab in tabs"
        :key="tab.id"
        class="tab-item"
        :class="{ active: activeTab === tab.id }"
        @click="activeTab = tab.id"
      >
        {{ tab.name }}
      </div>
    </div>

    <div class="tab-content">
      <!-- 用户管理 -->
      <div v-if="activeTab === 'users'" class="users-management">
        <div class="content-header">
          <h2>用户管理</h2>
          <div class="actions">
            <div class="search-box">
              <input type="text" v-model="searchQuery" placeholder="搜索用户名、邮箱或姓名" />
              <button class="btn btn-search" @click="searchUsers">搜索</button>
            </div>
            <button class="btn btn-primary" @click="showAddUserModal = true">添加用户</button>
          </div>
        </div>

        <div class="table-container">
          <table class="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>姓名</th>
                <th>邮箱</th>
                <th>角色</th>
                <th>状态</th>
                <th>注册时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in users" :key="user.id">
                <td>{{ user.id }}</td>
                <td>{{ user.username }}</td>
                <td>{{ user.realName || '-' }}</td>
                <td>{{ user.email }}</td>
                <td>
                  <span :class="getRoleClass(user.role)">{{ getRoleText(user.role) }}</span>
                </td>
                <td>
                  <span :class="getStatusClass(user.status)">{{ getStatusText(user.status) }}</span>
                </td>
                <td>{{ formatDate(user.createdAt) }}</td>
                <td class="actions-cell">
                  <button class="btn btn-sm btn-edit" @click="editUser(user)">编辑</button>
                  <button
                    class="btn btn-sm"
                    :class="user.status === 'active' ? 'btn-disable' : 'btn-enable'"
                    @click="toggleUserStatus(user)"
                  >
                    {{ user.status === 'active' ? '禁用' : '启用' }}
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="pagination">
          <button
            class="btn btn-sm btn-outline"
            :disabled="currentPage === 1"
            @click="changePage(currentPage - 1)"
          >
            上一页
          </button>
          <span class="page-info">第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
          <button
            class="btn btn-sm btn-outline"
            :disabled="currentPage === totalPages"
            @click="changePage(currentPage + 1)"
          >
            下一页
          </button>
        </div>
      </div>

      <!-- 系统设置 -->
      <div v-if="activeTab === 'settings'" class="system-settings">
        <div class="content-header">
          <h2>系统设置</h2>
        </div>

        <div class="settings-form">
          <form @submit.prevent="saveSettings">
            <div class="form-section">
              <h3>基本设置</h3>
              <div class="form-group">
                <label for="siteName">网站名称</label>
                <input type="text" id="siteName" v-model="settings.siteName" />
              </div>

              <div class="form-group">
                <label for="siteDescription">网站描述</label>
                <textarea
                  id="siteDescription"
                  v-model="settings.siteDescription"
                  rows="3"
                ></textarea>
              </div>

              <div class="form-group">
                <label for="contactEmail">联系邮箱</label>
                <input type="email" id="contactEmail" v-model="settings.contactEmail" />
              </div>
            </div>

            <div class="form-section">
              <h3>注册设置</h3>
              <div class="form-group checkbox-group">
                <label class="checkbox-label">
                  <input type="checkbox" v-model="settings.allowRegistration" />
                  允许新用户注册
                </label>
              </div>

              <div class="form-group checkbox-group">
                <label class="checkbox-label">
                  <input type="checkbox" v-model="settings.requireEmailVerification" />
                  要求邮箱验证
                </label>
              </div>

              <div class="form-group">
                <label for="defaultUserRole">默认用户角色</label>
                <select id="defaultUserRole" v-model="settings.defaultUserRole">
                  <option value="student">学生</option>
                  <option value="teacher">教师</option>
                </select>
              </div>
            </div>

            <div class="form-actions">
              <button type="submit" class="btn btn-primary" :disabled="isSubmitting">
                {{ isSubmitting ? '保存中...' : '保存设置' }}
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- 数据备份 -->
      <div v-if="activeTab === 'backup'" class="data-backup">
        <div class="content-header">
          <h2>数据备份</h2>
        </div>

        <div class="backup-actions">
          <button class="btn btn-primary" @click="createBackup">创建备份</button>
          <button class="btn btn-outline" @click="refreshBackups">刷新列表</button>
        </div>

        <div class="table-container">
          <table class="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>文件名</th>
                <th>大小</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="backup in backups" :key="backup.id">
                <td>{{ backup.id }}</td>
                <td>{{ backup.filename }}</td>
                <td>{{ formatFileSize(backup.size) }}</td>
                <td>{{ formatDate(backup.createdAt) }}</td>
                <td class="actions-cell">
                  <button class="btn btn-sm btn-outline" @click="downloadBackup(backup)">
                    下载
                  </button>
                  <button class="btn btn-sm btn-danger" @click="confirmDeleteBackup(backup)">
                    删除
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 添加用户弹窗 -->
    <div v-if="showAddUserModal" class="modal-overlay" @click="showAddUserModal = false">
      <div class="modal-content" @click.stop>
        <h2>添加用户</h2>
        <form @submit.prevent="addUser">
          <div class="form-group">
            <label for="newUsername">用户名</label>
            <input type="text" id="newUsername" v-model="newUser.username" required />
          </div>

          <div class="form-group">
            <label for="newEmail">邮箱</label>
            <input type="email" id="newEmail" v-model="newUser.email" required />
          </div>

          <div class="form-group">
            <label for="newPassword">密码</label>
            <input type="password" id="newPassword" v-model="newUser.password" required />
          </div>

          <div class="form-group">
            <label for="newRole">角色</label>
            <select id="newRole" v-model="newUser.role" required>
              <option value="student">学生</option>
              <option value="teacher">教师</option>
              <option value="admin">管理员</option>
            </select>
          </div>

          <div class="form-actions">
            <button type="button" class="btn btn-outline" @click="showAddUserModal = false">
              取消
            </button>
            <button type="submit" class="btn btn-primary">添加</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 标签页
const tabs = [
  { id: 'users', name: '用户管理' },
  { id: 'settings', name: '系统设置' },
  { id: 'backup', name: '数据备份' },
]
const activeTab = ref('users')

// 提交状态
const isSubmitting = ref(false)

// 统计数据
const stats = ref({
  totalUsers: 0,
  teacherUsers: 0,
  studentUsers: 0,
  totalTasks: 0,
})

// 用户管理相关
const searchQuery = ref('')
const currentPage = ref(1)
const totalPages = ref(1)
const users = ref<any[]>([])
const showAddUserModal = ref(false)
const newUser = ref({
  username: '',
  email: '',
  password: '',
  role: 'teacher',
})

// 系统设置
const settings = ref({
  siteName: 'ClassPrepHub 智能备课系统',
  siteDescription: '为教师提供智能化备课工具，提升教学效率和质量。',
  contactEmail: 'support@classprephub.com',
  allowRegistration: true,
  requireEmailVerification: true,
  defaultUserRole: 'teacher',
})

// 数据备份
const backups = ref<any[]>([])

// 加载统计数据
const loadStats = async () => {
  try {
    // 模拟加载数据
    await new Promise((resolve) => setTimeout(resolve, 500))

    // 实际项目中应从API获取数据
    stats.value = {
      totalUsers: 1256,
      teacherUsers: 987,
      studentUsers: 268,
      totalTasks: 4325,
    }
  } catch (error) {
    console.error('加载统计数据失败', error)
  }
}

// 加载用户数据
const loadUsers = async () => {
  try {
    // 模拟加载数据
    await new Promise((resolve) => setTimeout(resolve, 800))

    // 实际项目中应从API获取数据
    users.value = [
      {
        id: '1',
        username: 'teacher001',
        realName: '张老师',
        email: 'teacher001@example.com',
        role: 'teacher',
        status: 'active',
        createdAt: new Date('2022-09-01'),
      },
      {
        id: '2',
        username: 'student001',
        realName: '李同学',
        email: 'student001@example.com',
        role: 'student',
        status: 'active',
        createdAt: new Date('2022-09-05'),
      },
      {
        id: '3',
        username: 'admin001',
        realName: '王管理',
        email: 'admin001@example.com',
        role: 'admin',
        status: 'active',
        createdAt: new Date('2022-08-15'),
      },
      {
        id: '4',
        username: 'teacher002',
        realName: '赵老师',
        email: 'teacher002@example.com',
        role: 'teacher',
        status: 'disabled',
        createdAt: new Date('2022-09-10'),
      },
      {
        id: '5',
        username: 'student002',
        realName: '刘同学',
        email: 'student002@example.com',
        role: 'student',
        status: 'active',
        createdAt: new Date('2022-09-15'),
      },
    ]

    totalPages.value = 3 // 模拟总页数
  } catch (error) {
    console.error('加载用户数据失败', error)
  }
}

// 加载备份数据
const loadBackups = async () => {
  try {
    // 模拟加载数据
    await new Promise((resolve) => setTimeout(resolve, 600))

    // 实际项目中应从API获取数据
    backups.value = [
      {
        id: '1',
        filename: 'backup-20230320-120000.zip',
        size: 1024 * 1024 * 5.2, // 5.2MB
        createdAt: new Date('2023-03-20T12:00:00'),
      },
      {
        id: '2',
        filename: 'backup-20230315-120000.zip',
        size: 1024 * 1024 * 4.8, // 4.8MB
        createdAt: new Date('2023-03-15T12:00:00'),
      },
      {
        id: '3',
        filename: 'backup-20230310-120000.zip',
        size: 1024 * 1024 * 4.5, // 4.5MB
        createdAt: new Date('2023-03-10T12:00:00'),
      },
    ]
  } catch (error) {
    console.error('加载备份数据失败', error)
  }
}

// 用户相关方法
const searchUsers = () => {
  // 实际项目中应调用API进行搜索
  if (!searchQuery.value.trim()) {
    loadUsers()
    return
  }

  // 模拟搜索结果
  users.value = users.value.filter(
    (user) =>
      user.username.includes(searchQuery.value) ||
      user.email.includes(searchQuery.value) ||
      (user.realName && user.realName.includes(searchQuery.value)),
  )
}

const changePage = (page: number) => {
  currentPage.value = page
  loadUsers() // 实际项目中应带上分页参数
}

const editUser = (user: any) => {
  // 实际项目中应实现编辑用户的逻辑
  alert(`编辑用户: ${user.username}`)
}

const toggleUserStatus = (user: any) => {
  // 实际项目中应调用API修改用户状态
  user.status = user.status === 'active' ? 'disabled' : 'active'
  alert(`用户 ${user.username} 状态已修改为 ${getStatusText(user.status)}`)
}

const addUser = async () => {
  try {
    // 模拟添加用户
    await new Promise((resolve) => setTimeout(resolve, 1000))

    // 实际项目中应调用API添加用户
    const newId = (parseInt(users.value[users.value.length - 1].id) + 1).toString()

    users.value.push({
      id: newId,
      username: newUser.value.username,
      realName: '',
      email: newUser.value.email,
      role: newUser.value.role,
      status: 'active',
      createdAt: new Date(),
    })

    // 重置表单
    newUser.value = {
      username: '',
      email: '',
      password: '',
      role: 'teacher',
    }

    // 关闭弹窗
    showAddUserModal.value = false

    alert('用户添加成功')
  } catch (error) {
    console.error('添加用户失败', error)
    alert('添加用户失败，请重试')
  }
}

// 系统设置方法
const saveSettings = async () => {
  try {
    isSubmitting.value = true

    // 模拟保存设置
    await new Promise((resolve) => setTimeout(resolve, 1000))

    // 实际项目中应调用API保存设置
    alert('系统设置已保存')
  } catch (error) {
    console.error('保存设置失败', error)
    alert('保存失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

// 数据备份方法
const createBackup = async () => {
  try {
    // 模拟创建备份
    await new Promise((resolve) => setTimeout(resolve, 2000))

    // 实际项目中应调用API创建备份
    const now = new Date()
    const formattedDate = now
      .toISOString()
      .replace(/[-:T.]/g, '')
      .slice(0, 14)
    const filename = `backup-${formattedDate}.zip`

    backups.value.unshift({
      id: (parseInt(backups.value[0].id) + 1).toString(),
      filename,
      size: 1024 * 1024 * 5.5, // 5.5MB
      createdAt: now,
    })

    alert('备份创建成功')
  } catch (error) {
    console.error('创建备份失败', error)
    alert('创建备份失败，请重试')
  }
}

const refreshBackups = () => {
  loadBackups()
}

const downloadBackup = (backup: any) => {
  // 实际项目中应实现下载逻辑
  alert(`下载备份: ${backup.filename}`)
}

const confirmDeleteBackup = (backup: any) => {
  // 实际项目中应实现删除确认和删除逻辑
  if (confirm(`确定要删除备份 ${backup.filename} 吗？`)) {
    backups.value = backups.value.filter((item) => item.id !== backup.id)
    alert('备份已删除')
  }
}

// 辅助方法
const getRoleText = (role: string) => {
  const roleMap: Record<string, string> = {
    teacher: '教师',
    student: '学生',
    admin: '管理员',
  }
  return roleMap[role] || '未知'
}

const getRoleClass = (role: string) => {
  return `role-${role}`
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '正常',
    disabled: '禁用',
  }
  return statusMap[status] || '未知'
}

const getStatusClass = (status: string) => {
  return `status-${status}`
}

const formatDate = (date: Date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  })
}

const formatFileSize = (bytes: number) => {
  if (bytes < 1024) {
    return bytes + ' B'
  } else if (bytes < 1024 * 1024) {
    return (bytes / 1024).toFixed(2) + ' KB'
  } else if (bytes < 1024 * 1024 * 1024) {
    return (bytes / (1024 * 1024)).toFixed(2) + ' MB'
  } else {
    return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
  }
}

onMounted(() => {
  loadStats()
  loadUsers()
  loadBackups()
})
</script>

<style scoped>
.admin-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

h1 {
  margin-bottom: 24px;
  color: #333;
}

h2 {
  margin: 0;
  color: #333;
  font-size: 1.5rem;
}

h3 {
  margin-top: 0;
  margin-bottom: 16px;
  color: #444;
  font-size: 1.2rem;
}

.admin-stats {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-card h3 {
  color: #666;
  margin-bottom: 10px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #4caf50;
}

.admin-tabs {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 24px;
}

.tab-item {
  padding: 16px 24px;
  cursor: pointer;
  color: #666;
  font-weight: 500;
  border-bottom: 3px solid transparent;
  transition: all 0.3s;
}

.tab-item:hover {
  color: #4caf50;
}

.tab-item.active {
  color: #4caf50;
  border-bottom-color: #4caf50;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.actions {
  display: flex;
  gap: 16px;
}

.search-box {
  display: flex;
  gap: 8px;
}

.search-box input {
  width: 250px;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.table-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 24px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th {
  background-color: #f5f5f5;
  padding: 12px 16px;
  text-align: left;
  font-weight: 500;
  color: #333;
}

.data-table td {
  padding: 12px 16px;
  border-top: 1px solid #eee;
}

.actions-cell {
  display: flex;
  gap: 8px;
}

.role-teacher {
  display: inline-block;
  padding: 2px 8px;
  background-color: #e3f2fd;
  color: #1976d2;
  border-radius: 4px;
  font-size: 0.9rem;
}

.role-student {
  display: inline-block;
  padding: 2px 8px;
  background-color: #e8f5e9;
  color: #4caf50;
  border-radius: 4px;
  font-size: 0.9rem;
}

.role-admin {
  display: inline-block;
  padding: 2px 8px;
  background-color: #fce4ec;
  color: #e91e63;
  border-radius: 4px;
  font-size: 0.9rem;
}

.status-active {
  display: inline-block;
  padding: 2px 8px;
  background-color: #e8f5e9;
  color: #4caf50;
  border-radius: 4px;
  font-size: 0.9rem;
}

.status-disabled {
  display: inline-block;
  padding: 2px 8px;
  background-color: #f5f5f5;
  color: #9e9e9e;
  border-radius: 4px;
  font-size: 0.9rem;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
}

.page-info {
  color: #666;
}

.form-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.checkbox-group {
  margin-bottom: 12px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

input,
textarea,
select {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

textarea {
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
  gap: 12px;
}

.backup-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
}

.btn {
  padding: 10px 20px;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  border: none;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 0.9rem;
}

.btn-search {
  background-color: #f5f5f5;
  color: #333;
}

.btn-outline {
  background-color: transparent;
  border: 1px solid #4caf50;
  color: #4caf50;
}

.btn-primary {
  background-color: #4caf50;
  color: white;
}

.btn-edit {
  background-color: #2196f3;
  color: white;
}

.btn-danger {
  background-color: #f44336;
  color: white;
}

.btn-disable {
  background-color: #f44336;
  color: white;
}

.btn-enable {
  background-color: #4caf50;
  color: white;
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
}

.modal-content h2 {
  margin-top: 0;
  margin-bottom: 24px;
}

@media (max-width: 768px) {
  .admin-container {
    padding: 16px;
  }

  .admin-stats {
    grid-template-columns: 1fr;
  }

  .content-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .actions {
    width: 100%;
    flex-direction: column;
  }

  .search-box {
    width: 100%;
  }

  .search-box input {
    flex: 1;
  }
}
</style>
